import { Button, Table, Tag } from 'antd'
import CommonDialog from '@/components/commonDialog'
import { useState, useEffect } from 'react'

export function ModelTable({
    title,
    rowkey,
    rowName,
    Columns,
    Api,
    handleSelect, // 新增：父组件传入的回调
    initialRows = [], // ✅ 新增：从表单传进来的已选经销商
}: {
    title: string
    rowkey: string
    rowName: string
    Columns: any[]
    Api: (params?: any) => Promise<any>
    handleSelect?: (rows: any[]) => void // 新增：类型声明
    initialRows?: any[] // ✅ 类型声明
}) {
    const [dialogOpen, setDialogOpen] = useState(false)
    const [confirmLoading, setConfirmLoading] = useState(false)
    const [tableParams, setTableParams] = useState({
        pagination: {
            current: 1,
            pageSize: 10,
        },
    })
    const [loading, setLoading] = useState(false)
    const [total, setTotal] = useState(0)
    const [dataSource, setDataSource] = useState<Array<any>>([])
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
    const [dataSelectedRows, setSelectedRows] = useState<any[]>([])

    // 新增：真正确认后的选中，用来展示 Tag
    const [confirmedRowKeys, setConfirmedRowKeys] = useState<React.Key[]>([])
    const [confirmedRows, setConfirmedRows] = useState<any[]>([])

    const onSelectChange = (
        newSelectedRowKeys: React.Key[],
        selectedRows: any[]
    ) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys)
        console.log('selected usernames: ', selectedRows)
        setSelectedRows(selectedRows)
        setSelectedRowKeys(newSelectedRowKeys)
    }

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
        preserveSelectedRowKeys: true, // 保留已选择的行
    }
    function fetchData(values = {}) {
        const pageData = {
            page: tableParams.pagination?.current,
            pageSize: tableParams.pagination?.pageSize,
            ...values,
        }
        setLoading(true)
        Api(pageData)
            .then((res: any) => {
                setDataSource(res.data.list)
                setTotal(res.data.total)
            })
            .finally(() => {
                setLoading(false)
            })
    }
    // ✅ 初次挂载/initialRows 变化时，用它初始化 confirmed*
    useEffect(() => {
        if (initialRows && initialRows.length > 0) {
            setConfirmedRows(initialRows)
            setConfirmedRowKeys(initialRows.map((item) => item[rowkey]))
        } else {
            setConfirmedRows([])
            setConfirmedRowKeys([])
        }
    }, [initialRows, rowkey])
    // 1. 打开弹窗时：重置分页到第一页，并拉一次数据
    useEffect(() => {
        if (dialogOpen) {
            // 重置到第一页
            setTableParams((prev) => ({
                ...prev,
                pagination: {
                    ...prev.pagination,
                    current: 1,
                },
            }))
            // 直接调一次接口
            fetchData()
        }
    }, [dialogOpen])

    // 2. 分页变化时：在弹窗打开状态下再拉数据
    useEffect(() => {
        if (!dialogOpen) return // 关闭状态不请求
        fetchData()
    }, [tableParams])
    function handleDialogOk() {
        setConfirmLoading(true)
        setTimeout(() => {
            // 更新已确认的选中
            setConfirmedRowKeys(selectedRowKeys)
            setConfirmedRows(dataSelectedRows)

            // 调用父组件回调，把“已确认”的选中传出去
            handleSelect?.(dataSelectedRows)

            setConfirmLoading(false)
            setDialogOpen(false)
        }, 200)
    }
    function handleDialogCancel() {
        setDialogOpen(false)
    }
    function openDialog() {
        // 用已确认的选中作为当前弹窗里的初始勾选
        setSelectedRowKeys(confirmedRowKeys)
        setSelectedRows(confirmedRows)
        // 打开选择经销商的对话框的逻辑
        setDialogOpen(true)
    }
    function handleClose(value: React.Key) {
        // 从已确认里删除
        const newConfirmedRowKeys = confirmedRowKeys.filter(
            (key) => key !== value
        )
        const newConfirmedRows = confirmedRows.filter(
            (item) => item[rowkey] !== value
        )
        setConfirmedRowKeys(newConfirmedRowKeys)
        setConfirmedRows(newConfirmedRows)

        // 同时同步给父组件
        handleSelect?.(newConfirmedRows)
    }
    function handleClear() {
        setConfirmedRowKeys([])
        setConfirmedRows([])
        handleSelect?.([])
    }
    return (
        <div>
            <Button type="primary" onClick={openDialog} size="small">
                {title}
            </Button>
            <div
                style={{
                    display: confirmedRows.length > 0 ? 'block' : 'none',
                }}
                className="w-full min-h-10 border border-light-800 rounded-sm p-2"
            >
                {
                    /* 在这里可以显示已选择的经销商列表 */
                    confirmedRows.map((item) => (
                        <Tag
                            key={item[rowkey]}
                            closable
                            onClose={() => handleClose(item[rowkey])}
                        >
                            {item[rowName] ?? ''}
                        </Tag>
                    ))
                }

                <Button
                    type="link"
                    className="float-right"
                    onClick={handleClear}
                >
                    清空
                </Button>
            </div>
            <CommonDialog
                open={dialogOpen}
                title={title}
                width={1400}
                confirmLoading={confirmLoading}
                onOk={handleDialogOk}
                onCancel={handleDialogCancel}
            >
                <Table
                    rowSelection={rowSelection}
                    loading={loading}
                    columns={Columns}
                    dataSource={dataSource}
                    rowKey={rowkey}
                    pagination={{
                        current: tableParams.pagination?.current,
                        pageSize: tableParams.pagination?.pageSize,
                        total, // 确保有 total
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: () => `共 ${total} 条`,
                        onChange: (page, pageSize) => {
                            setTableParams((prev) => ({
                                ...prev,
                                pagination: {
                                    ...prev.pagination,
                                    current: page,
                                    pageSize,
                                },
                            }))
                        },
                    }}
                />
            </CommonDialog>
        </div>
    )
}
